package com.incito.crawl.common.httpclient;

import com.incito.crawl.common.utils.proxy.ProxyInfo;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by wuyu on 2014/12/9.
 * 从CrawlHttpClientContext中获取直接设置的ProxyInfo代理信息
 */
public class CrawlContextProxyRoutePlanner extends DefaultRoutePlanner {
    private static Logger logger = LoggerFactory.getLogger("crawldesc");


    public CrawlContextProxyRoutePlanner() {
        super(null);
    }

    @Override
    protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
        HttpRequestWrapper requestWrapper = (HttpRequestWrapper) request;
        CrawlHttpClientContext crawlHttpClientContext = null;
        HttpHost proxy = null;
        if (context instanceof CrawlHttpClientContext) {
            crawlHttpClientContext = (CrawlHttpClientContext) context;
            ProxyInfo proxyInfo = crawlHttpClientContext.getProxyInfo();
            if (proxyInfo != null) {
                logger.info("getProxy-ip:{},port:{}", proxyInfo.getIp(), proxyInfo.getPort());
                proxy = new HttpHost(proxyInfo.getIp(), proxyInfo.getPort());
                requestWrapper.getOriginal().setHeader("X-Forwarded-For", proxy.toHostString());
                return proxy;
            }
        }
        return super.determineProxy(target, request, context);
    }
}
